package com.pine.dbant.common.plugin.meta;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author huangli
 * @date 2021/5/19
 */
public class AbstractMetaAnalysisFilter implements MetaAnalysisFilter {
    /**
     * 被忽略的表名模式
     */
    protected static final Pattern IGNORE_PATTEN = Pattern.compile("[~!@#$%^&*=+]");

    /**
     * 忽略采集的数据库
     */
    private List<String> ignoreCatalogs = new ArrayList<>();
    /**
     * 忽略采集的schema
     */
    private List<String> ignoreSchemas = new ArrayList<>();
    /**
     * 忽略采集的表名称
     */
    private List<String> ignoreTables = new ArrayList<>();

    /**
     * 过滤catalog
     */
    @Override
    public MetaAnalysisFilter ignoreCatalogs(List<String> catalogs) {
        this.ignoreCatalogs.addAll(catalogs);
        return this;
    }

    /**
     * 过滤schema
     */
    @Override
    public MetaAnalysisFilter ignoreSchemas(List<String> schemas) {
        this.ignoreSchemas.addAll(schemas);
        return this;
    }

    /**
     * 过滤 表名
     * @param tbNames
     */
    @Override
    public MetaAnalysisFilter ignoreTableNames(List<String> tbNames) {
        this.ignoreTables.addAll(tbNames);
        return this;
    }

    @Override
    public boolean checkIgnoreCatalog(String catalog) {
        if (CollectionUtils.isEmpty(ignoreCatalogs) || StringUtils.isEmpty(catalog)) {
            return false;
        }
        return ignoreCatalogs.contains(catalog);
    }

    @Override
    public boolean checkIgnoreSchema(String schema) {
        if (CollectionUtils.isEmpty(ignoreSchemas) || StringUtils.isEmpty(schema)) {
            return false;
        }
        return ignoreSchemas.contains(schema) || IGNORE_PATTEN.matcher(schema).find();
    }

    @Override
    public boolean checkIgnoreTableName(String tbName) {
        if (CollectionUtils.isEmpty(ignoreTables) || StringUtils.isEmpty(tbName)) {
            return false;
        }
        return ignoreTables.contains(tbName) || IGNORE_PATTEN.matcher(tbName).find();
    }
}
